import router from '@/router'

//@ts-expect-error@ts-ignore
import nprogress from 'nprogress'

import 'nprogress/nprogress.css'
import { GET_TOKEN } from './utils/token'
import { useUserStore } from './store/modules/user'

nprogress.configure({ showSpinner: false })
import pinia from './store'
const userStore = useUserStore(pinia)
router.beforeEach(async (to, from , next) => {
    document.title = ` - ${to.meta.title}`
    nprogress.start()

    const token = GET_TOKEN()
    const username = userStore.username;
    if(token) {
        if(to.path == '/login') {
            next({path: '/'})
        }else {
            if(username) {
                next()
            }else {
                // 重新获取用户信息
                try {
                    await userStore.userInfo()
                    next({...to})
                } catch (error) {
                    await userStore.userLogout()
                    next({
                        path: '/login',
                        query: {redirect: to.path}
                    })
                }
            }
        }
    }else {
        //用户未登录判断
        if (to.path == '/login') {
          next()
        } else {
          next({ path: '/login', query: { redirect: to.path } })
        }
    }
})

// 结束后
router.afterEach(() => {
    nprogress.done()
})